import React, { useState, useEffect, useRef } from "react";
import { SketchPicker } from "react-color";
import dynamic from "next/dynamic";

// 动态导入Quill以避免SSR问题
const Quill = dynamic(() => import("quill"), {
  ssr: false,
  loading: () => <p>加载编辑器中...</p>,
});

// 确保样式只在客户端加载
const QuillCSS = () => {
  useEffect(() => {
    import("quill/dist/quill.snow.css");
  }, []);
  return null;
};

interface MarkdownEditorProps {
  initialContent: string;
  onChange: (content: string) => void;
  onSave: (content: string) => void;
}

export default function MarkdownEditor({
  initialContent,
  onChange,
  onSave,
}: MarkdownEditorProps) {
  const [content, setContent] = useState(initialContent);
  const [textColor, setTextColor] = useState<string>("#000000");
  const [bgColor, setBgColor] = useState<string>("#ffffff");
  const [showTextColorPicker, setShowTextColorPicker] =
    useState<boolean>(false);
  const [showBgColorPicker, setShowBgColorPicker] = useState<boolean>(false);

  const editorRef = useRef<HTMLDivElement>(null);
  const quillRef = useRef<any>(null);

  // 初始化Quill编辑器
  useEffect(() => {
    if (!editorRef.current || typeof Quill !== "function") return;

    // 导入模块后再进行初始化
    Promise.all([import("quill")]).then(([{ default: Quill }]) => {
      // 配置Quill工具栏
      const toolbarOptions = [
        [{ header: [1, 2, 3, false] }],
        ["bold", "italic", "underline", "strike"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["blockquote", "code-block"],
        [{ color: [] }, { background: [] }],
        ["link", "image"],
        ["clean"],
      ];

      // 创建Quill编辑器实例
      if (!quillRef.current) {
        quillRef.current = new Quill(editorRef.current, {
          modules: {
            toolbar: toolbarOptions,
          },
          placeholder: "开始编辑内容...",
          theme: "snow",
        });

        // 确保root存在后再设置初始内容
        if (quillRef.current.root) {
          quillRef.current.root.innerHTML = initialContent;
        }

        // 监听内容变化
        quillRef.current.on("text-change", () => {
          const newContent = quillRef.current.root.innerHTML;
          setContent(newContent);
          onChange(newContent);
        });
      }
    });

    // 清理函数
    return () => {
      if (quillRef.current) {
        // 某些清理操作（如果需要）
      }
    };
  }, [editorRef, initialContent, onChange]);

  // 当初始内容变化时更新编辑器内容
  useEffect(() => {
    if (
      quillRef.current &&
      quillRef.current.root &&
      initialContent !== quillRef.current.root.innerHTML
    ) {
      quillRef.current.root.innerHTML = initialContent;
    }
  }, [initialContent]);

  // 应用文本颜色
  const applyTextColor = () => {
    if (quillRef.current) {
      const range = quillRef.current.getSelection();
      if (range) {
        if (range.length > 0) {
          quillRef.current.format("color", textColor);
        } else {
          quillRef.current.format("color", textColor);
        }
      }
    }
    setShowTextColorPicker(false);
  };

  // 应用背景颜色
  const applyBackgroundColor = () => {
    if (quillRef.current) {
      const range = quillRef.current.getSelection();
      if (range) {
        if (range.length > 0) {
          quillRef.current.format("background", bgColor);
        } else {
          quillRef.current.format("background", bgColor);
        }
      }
    }
    setShowBgColorPicker(false);
  };

  // 插入表格
  const insertTable = () => {
    if (!quillRef.current) return;

    const rowsInput = prompt("请输入行数", "3");
    if (!rowsInput) return;

    const colsInput = prompt("请输入列数", "3");
    if (!colsInput) return;

    const rows = parseInt(rowsInput) || 3;
    const cols = parseInt(colsInput) || 3;

    // 创建表格HTML
    let tableHTML = '<table style="width:100%; border-collapse: collapse;">';
    // 添加表头
    tableHTML += "<thead><tr>";
    for (let i = 0; i < cols; i++) {
      tableHTML +=
        '<th style="border: 1px solid #ddd; padding: 8px; text-align: left;">标题</th>';
    }
    tableHTML += "</tr></thead>";
    // 添加表体
    tableHTML += "<tbody>";
    for (let i = 0; i < rows - 1; i++) {
      tableHTML += "<tr>";
      for (let j = 0; j < cols; j++) {
        tableHTML +=
          '<td style="border: 1px solid #ddd; padding: 8px;">内容</td>';
      }
      tableHTML += "</tr>";
    }
    tableHTML += "</tbody></table>";

    // 插入表格
    const range = quillRef.current.getSelection();
    if (range) {
      quillRef.current.clipboard.dangerouslyPasteHTML(range.index, tableHTML);
    }
  };

  // 保存内容
  const handleSave = () => {
    onSave(content);
  };

  return (
    <div className='flex flex-col h-full'>
      <QuillCSS />
      <div className='mb-4 flex justify-between items-center'>
        <button
          onClick={handleSave}
          className='px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600'
        >
          保存
        </button>
      </div>
      <div className='border rounded flex-1 quill-container'>
        <div ref={editorRef} className='h-full' />
      </div>
    </div>
  );
}
